<route lang="yaml">
  meta:
    title: 待分拣
</route>

<script setup lang="ts">
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { ref } from 'vue'

const detailDialogVisible = ref(false)
const currentSortId = ref<string>('')
const filteredHistory = ref<SortHistory[]>([])

interface SortHistory {
  id: string
  sortId: string // 关联分拣单ID
  productName: string
  sortedNum: number
  timestamp: string
}

// 模拟分拣历史数据
const sortHistoryData = ref<SortHistory[]>([
  { id: 'H001', sortId: 'S001', productName: '笔记本电脑', sortedNum: 20, timestamp: '2025-04-01 10:00' },
  { id: 'H002', sortId: 'S001', productName: '笔记本电脑', sortedNum: 30, timestamp: '2025-04-01 11:00' },
  { id: 'H003', sortId: 'S002', productName: '无线鼠标', sortedNum: 120, timestamp: '2025-04-01 14:00' },
])
interface Project {
  id: string
  productId: string
  productName: string
  quantity: number // 待分拣的数量
  supplierName: string
  price: number
  weight: number
  size: string
  status: StatusType
  sortNum: number // 已分拣的数量
}

type StatusType = '待分拣' | '分拣中' | '已完成' | '已取消'

const dialogVisible = ref(false)
const statusColors: Record<StatusType, 'success' | 'warning' | 'info' | 'danger'> = {
  待分拣: 'info',
  分拣中: 'warning',
  已完成: 'success',
  已取消: 'danger',
}

const sortNum = ref(0) // 原const sortNum = 0改为ref
const currentRow = ref<Project>() // 新增当前行引用
const tableData = ref<Project[]>([
  { // 待分拣状态示例
    id: 'S001',
    productId: 'P1001',
    productName: '笔记本电脑',
    supplierName: '戴尔供应商',
    quantity: 50,
    price: 6999.00,
    weight: 3.2,
    size: '40×30×5',
    status: '待分拣',
    sortNum: 0,
  },
  { // 分拣中状态示例
    id: 'S002',
    productId: 'P2002',
    productName: '无线鼠标',
    supplierName: '罗技科技',
    quantity: 200,
    price: 199.00,
    weight: 0.15,
    size: '12×6×3',
    status: '分拣中',
    sortNum: 120,
  },
  { // 已完成状态示例
    id: 'S003',
    productId: 'P3003',
    productName: '机械键盘',
    supplierName: '樱桃中国',
    quantity: 80,
    price: 899.00,
    weight: 1.2,
    size: '44×14×4',
    status: '已完成',
    sortNum: 80,
  },
])

const selectedRows = ref<Project[]>([])
const searchKeyword = ref('')

// 调整分页样式配置
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(1000) // 模拟总数据量

// async function handleStartSorting() {
//   const validSelections = selectedRows.value.filter(item => item.status === '待分拣')
//   if (validSelections.length === 0) {
//     ElMessage.warning('请选择待分拣状态的记录')
//     return
//   }
//   validSelections.forEach((row) => {
//     row.status = '分拣中'
//   })
// }

async function handleComplete() {
  const validSelections = selectedRows.value.filter(item => item.status === '分拣中')
  if (validSelections.length === 0) {
    ElMessage.warning('请选择分拣中状态的记录')
    return
  }
  validSelections.forEach((row) => {
    row.status = '已完成'
  })
}

// async function handleRowOperation(row: Project) {
//   try {
//     const action = row.status === '待分拣' ? '开始分拣' : '完成分拣'
//     if (row.status === '待分拣') {
//       currentRow.value = row // 存储当前行引用
//       sortNum.value = 0 // 重置分拣数量
//       dialogVisible.value = true
//       return // 提前返回避免直接修改状态
//     }
//     await ElMessageBox.confirm(
//       `确定要${action}【${row.productName}】吗？`,
//       `${action}确认`,
//       {
//         confirmButtonText: '确认',
//         cancelButtonText: '取消',
//         type: 'warning',
//       },
//     )

//     row.status = '分拣中'
//   }
//   catch {
//     ElMessage.info('已取消操作')
//   }
// }
function confirmSort() {
  if (currentRow.value && sortNum.value > 0) {
    currentRow.value.sortNum = sortNum.value
    currentRow.value.status = '分拣中'
    dialogVisible.value = false
  }
}
// 分拣操作（开始/继续）
async function handleSortOperation(row: Project) {
  try {
    if (row.status === '待分拣') {
      // 初始化分拣操作
      currentRow.value = row
      sortNum.value = 0
      dialogVisible.value = true
      return
    }

    // 继续分拣确认
    await ElMessageBox.confirm(
      `是否继续分拣【${row.productName}】？`,
      '继续分拣确认',
      {
        confirmButtonText: '继续分拣',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    currentRow.value = row
    sortNum.value = row.quantity - row.sortNum // 默认填充剩余数量
    dialogVisible.value = true
  }
  catch {
    ElMessage.info('已取消操作')
  }
}

// 单个完成分拣
async function handleCompleteSingle(row: Project) {
  try {
    await ElMessageBox.confirm(
      `确认完成【${row.productName}】的全部分拣任务？`,
      '完成分拣确认',
      {
        confirmButtonText: '确认完成',
        cancelButtonText: '取消',
        type: 'success',
      },
    )
    row.status = '已完成'
    ElMessage.success(`${row.productName} 已完成分拣`)
  }
  catch {
    ElMessage.info('已取消操作')
  }
}
// 撤回操作
async function handleRecall() {

}
function showDetail(sortId: string) {
  currentSortId.value = sortId
  filteredHistory.value = sortHistoryData.value.filter(item => item.sortId === sortId)
  detailDialogVisible.value = true
}
</script>

<template>
  <div>
    <FaPageMain>
      <!-- 调整操作栏布局 -->
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button
            type="success"
            style="margin-left: 12px;"
            @click="handleComplete"
          >
            <el-icon><Select /></el-icon>
            <span class="ml-1">批量完成分拣</span>
          </el-button>
          <el-button
            type="danger"
            style="margin-left: 12px;"
            @click="handleRecall"
          >
            <el-icon><Refresh /></el-icon>
            <span class="ml-1">撤回操作</span>
          </el-button>
        </div>

        <!-- 新增搜索框 -->
        <div class="search-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索分拣单号/产品名称"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 调整表格样式 -->
      <div class="table-wrapper">
        <ElTable
          :data="tableData"
          row-key="id"
          style="width: 100%;"
          max-height="calc(100vh - 200px)"
          :fit="true"
          stripe
          @selection-change="(val: Project[]) => selectedRows = val"
        >
          <!-- 修改表格列定义 -->
          <el-table-column
            type="selection"
            width="55"
            :selectable="(row: Project) => row.status === '待分拣' || row.status === '分拣中'"
          />
          <el-table-column prop="id" label="分拣单号" width="120">
            <template #default="{ row }">
              <a href="javascript:void(0)" class="text-blue-600 hover:underline" @click="showDetail(row.id)">
                {{ row.id }}
              </a>
            </template>
          </el-table-column>
          <el-table-column prop="productId" label="产品编号" width="120" />
          <el-table-column prop="productName" label="产品名称" />

          <el-table-column prop="supplierName" label="供应商" width="150" />
          <el-table-column prop="quantity" label="数量（箱）" width="120">
            <template #default="{ row }">
              {{ row.quantity }} 箱
            </template>
          </el-table-column>
          <el-table-column prop="sortNum" label="已分拣（件）" width="120">
            <template #default="{ row }">
              {{ row.sortNum || 0 }} 件
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量（kg）" width="120" />
          <el-table-column prop="size" label="尺寸" width="100">
            <template #default="{ row }">
              {{ row.size }}cm³
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="140">
            <template #default="{ row }">
              <el-tag :type="statusColors[row.status as StatusType]" effect="dark">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="170" fixed="right">
            <template #default="{ row }">
              <!-- 可操作状态判断 -->
              <div v-if="['待分拣', '分拣中'].includes(row.status)">
                <!-- 分拣操作按钮 -->
                <el-button
                  v-if="row.sortNum < row.quantity"
                  :type="row.status === '待分拣' ? 'primary' : 'warning'"
                  size="small"
                  @click="handleSortOperation(row)"
                >
                  {{ row.status === '待分拣' ? '开始分拣' : '继续分拣' }}
                </el-button>

                <!-- 完成分拣按钮 -->
                <el-button
                  v-if="row.sortNum === row.quantity"
                  type="success"
                  size="small"
                  @click="handleCompleteSingle(row)"
                >
                  完成分拣
                </el-button>
              </div>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
        </ElTable>
      </div>

      <!-- 调整分页样式 -->
      <div class="pagination-wrapper" float-right>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </FaPageMain>

    <!-- 分拣操作弹窗组件 -->
    <el-dialog
      v-model="dialogVisible"
      title="分拣操作"
      width="500px"
    >
      <template v-if="currentRow">
        <div class="p-4">
          <div class="mb-4 flex items-center">
            <span class="w-24">产品名称：</span>
            <el-tag type="info">
              {{ currentRow.productName }}
            </el-tag>
          </div>

          <div class="flex items-center">
            <span class="w-24">分拣数量：</span>
            <el-input-number
              v-model="sortNum"
              :min="0"
              :max="currentRow.quantity"
              controls-position="right"
              :precision="0"
            />
            <span class="ml-2 text-gray-500">
              / {{ currentRow.quantity }} 件
            </span>
          </div>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!sortNum"
            @click="confirmSort"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 详情弹窗组件 -->
    <el-dialog v-model="detailDialogVisible" title="分拣记录详情" width="600px">
      <ElTable :data="filteredHistory" style="width: 100%;">
        <el-table-column prop="sortId" label="分拣单号" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="sortedNum" label="分拣数量" />
        <el-table-column prop="timestamp" label="分拣时间" />
      </ElTable>

      <template #footer>
        <el-button @click="detailDialogVisible = false">
          关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<!-- 新增样式部分 -->
<style scoped>
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.mb-4 {
  margin-bottom: 1rem;
}

.ml-1 {
  margin-left: 0.25rem;
}

.search-wrapper {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 16px;
}
</style>
